package com.mz.ozy.activity.me;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.LinearLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.mz.ozy.R;
import com.mz.ozy.adapter.ReturnGoodsListAdapter;
import com.mz.ozy.base.BaseActivity;
import com.mz.ozy.bean.CarGoodsBean;
import com.mz.ozy.bean.CarGoodsDetailBean;
import com.mz.ozy.mvp.presenter.ReturnPresenter;
import com.mz.ozy.mvp.view.RetunContract;
import com.mz.ozy.utils.Utils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import org.json.JSONObject;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2018/11/21.
 */

public class ReturnGoodsListActivity extends BaseActivity<RetunContract.View, ReturnPresenter> implements RetunContract.View {


    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.ll_no_data)
    LinearLayout llNoData;
    @BindView(R.id.srl_refresh)
    SmartRefreshLayout smartRefreshLayout;
    private ReturnGoodsListAdapter mAdapter;
    private int pageNo = 1;
    private int tag = 0;
    private List<CarGoodsBean.PageBean.PageItemsBean> mBeanList = new ArrayList<>();
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    boolean isCountDown = countDownTime();
                    if (isCountDown) {
                        mAdapter.notifyDataSetChanged();
                        handler.sendEmptyMessageDelayed(1, 1000);
                    }
                    break;

            }
        }
    };


    private void refreshList(boolean load) {
        if (mPresenter == null) return;
        tag = 0;
        pageNo = 1;
        mPresenter.onlist(ReturnGoodsListActivity.this, pageNo + "");
    }

    public static void start(Context context) {
        Intent starter = new Intent(context, ReturnGoodsListActivity.class);
        //starter.putExtra();
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_return_goods_list);
        ButterKnife.bind(this);
        initTitle();
        tvCenterTitle.setText("退换货列表");
        init();
    }

    @Override
    protected void onResume() {

        super.onResume();
        mPresenter.onlist(ReturnGoodsListActivity.this, pageNo + "");

    }

    private void init() {

        tvTitle.setText("退换货列表");
        recyclerview.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new ReturnGoodsListAdapter(mBeanList);
        mAdapter.setHasStableIds(true);
        recyclerview.setAdapter(mAdapter);
        smartRefreshLayout.setEnableAutoLoadmore(true);
        smartRefreshLayout.autoRefresh();
        smartRefreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                if (mPresenter == null) return;
                tag = 1;
                pageNo = pageNo + 1;
                mPresenter.onlist(ReturnGoodsListActivity.this, pageNo + "");
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                if (mPresenter == null) return;
                tag = 0;
                pageNo = 1;
                mPresenter.onlist(ReturnGoodsListActivity.this, pageNo + "");
            }
        });

        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                CarGoodsBean.PageBean.PageItemsBean itemsBean = mAdapter.getItem(position);
                // TODO: 2018/11/21
                Intent intent = new Intent(ReturnGoodsListActivity.this, ReturnGoodsListDetailsActivity.class);
                intent.putExtra("id", itemsBean.getTesq());
                startActivity(intent);
            }
        });
    }

    @Override
    public void onCanclInvite(JSONObject s) {

    }

    @Override
    public void onJh(JSONObject s) {

    }

    @Override
    public void onUpReturn(JSONObject s) {

    }

    @Override
    public void onlist(CarGoodsBean bean) {
        if (tag == 0) {
            smartRefreshLayout.setLoadmoreFinished(false);
            smartRefreshLayout.finishRefresh();
            mBeanList.clear();
            if (bean.getPage().getPageItems().size() == 0) {
                llNoData.setVisibility(View.VISIBLE);
            } else {
                llNoData.setVisibility(View.GONE);
            }
        } else if (tag == 1) {
            smartRefreshLayout.finishLoadmore();
        }
        mBeanList.addAll(bean.getPage().getPageItems());
        boolean isCountDown = setCountDownTime(bean.getDate());
        mAdapter.notifyDataSetChanged();
        handler.removeMessages(1);
        if (isCountDown) {
            handler.sendEmptyMessageDelayed(1, 1000);
        }
        if (bean.getPage().getPageItems().size() == 0 || bean.getPage().getPageSize() * bean.getPage().getPageNumber() >= bean.getPage().getPageTotle()) {
            smartRefreshLayout.setLoadmoreFinished(true);//将不会再次触发加载更多事件
        }
    }

    private boolean countDownTime() {
        boolean isCountDown = false;
        boolean reStart = false;
        if (mBeanList.size() > 0) {
            for (CarGoodsBean.PageBean.PageItemsBean pageItemBean : mBeanList) {
                if (pageItemBean.getState() == 0) {
                    pageItemBean.setSpaceTime(pageItemBean.getSpaceTime() - 1);
                    if (pageItemBean.getSpaceTime() > 0) {
                        isCountDown = true;
                    } else {
                        pageItemBean.setTimeOut(true);
                        reStart = true;
                    }
                }
            }
        }
        if (reStart) {
            isCountDown = false;
        }
        return isCountDown;
    }

    private boolean setCountDownTime(String data) {
        boolean isCountDown = false;
        if (mBeanList.size() > 0) {
            for (CarGoodsBean.PageBean.PageItemsBean pageItemBean : mBeanList) {
                if (pageItemBean.getState() == 0) {
                    if (startCountDown(pageItemBean, data)) {
                        isCountDown = true;
                    }
                }
            }
        }
        return isCountDown;
    }

    private boolean startCountDown(CarGoodsBean.PageBean.PageItemsBean pageItemBean, String created) {
        try {
            String compareDate = pageItemBean.getEndtime();
            final long nowInt = Utils.parseDateIntTime(created);
            final long endtimeInt = Utils.parseDateIntTime(compareDate);
            //  int coun = TimeUtils.getCountDownTime(endtime, created);
            if (endtimeInt > nowInt) {
                final long spaceTimeInt = (endtimeInt - nowInt) / 1000;
                pageItemBean.setSpaceTime(spaceTimeInt);
                return true;
            } else {
                pageItemBean.setTimeOut(true);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public void onlistDetail(CarGoodsDetailBean s) {

    }

    @Override
    public void onShDetail(CarGoodsDetailBean s) {

    }
}
